package com.ailanyin.modules.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.ailanyin.modules.system.domain.SysRole;
import com.ailanyin.modules.system.domain.SysUser;
import com.ailanyin.modules.system.service.ISysPostService;
import com.ailanyin.modules.system.service.ISysRoleService;
import com.ailanyin.modules.system.service.ISysUserService;
import com.github.pagehelper.PageHelper;
import com.ailanyin.common.base.result.AjaxResult;
import com.ailanyin.common.database.result.CommonPage;
import com.ailanyin.common.log.annotation.Log;
import com.ailanyin.common.log.enums.BusinessType;
import com.ailanyin.common.poi.utils.ExcelUtil;
import com.ailanyin.common.security.utils.SecurityUtil;
import io.swagger.annotations.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理 web层
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022-09-22 04:20:28
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysPostService postService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("hasAuthority('system:user:list')")
    @GetMapping("/list")
    public CommonPage list(SysUser user,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = userService.selectUserList(user);
        return CommonPage.restPage(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("hasAuthority('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil.exportExcel(list, SysUser.class, "用户数据", response);
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("hasAuthority('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        List<SysUser> list = ExcelUtil.importExcel(file, SysUser.class);
        String operName = SecurityUtil.getLoginUsername();
        String message = userService.importUser(list, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil.exportExcel(new ArrayList<>(), SysUser.class, "用户导入模板", response);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("hasAuthority('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (ObjectUtil.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            sysUser.setPassword(null);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("hasAuthority('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        user.setCreateBy(SecurityUtil.getLoginUsername());
        return AjaxResult.toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("hasAuthority('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtil.getLoginUsername());
        return AjaxResult.toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("hasAuthority('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return AjaxResult.toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("hasAuthority('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        return AjaxResult.toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("hasAuthority('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        return AjaxResult.toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("hasAuthority('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("hasAuthority('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return AjaxResult.success();
    }

    /**
     * 个人中心-个人信息
     */
    @GetMapping("/profile")
    public AjaxResult profile() {
        String username = SecurityUtil.getLoginUsername();
        AjaxResult ajax = AjaxResult.success(userService.selectUserByUserName(username));
        ajax.put("roleGroup", userService.selectUserRoleGroup(username));
        ajax.put("postGroup", userService.selectUserPostGroup(username));
        return ajax;
    }

    /**
     * 个人中心-修改密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/profile/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        userService.updatePwd(oldPassword, newPassword);
        return AjaxResult.success();
    }

    /**
     * 个人中心-修改头像
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/profile/uploadAvatar")
    public AjaxResult uploadAvatar(String url) {
        SysUser user = new SysUser();
        user.setUserId(SecurityUtil.getLoginUserId());
        user.setAvatar(url);
        userService.updateUserProfile(user);
        return AjaxResult.success();
    }

    /**
     * 个人中心-修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/profile")
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        user.setUserId(SecurityUtil.getLoginUserId());
        user.setPassword(null);
        user.setAvatar(null);
        user.setDeptId(null);
        userService.updateUserProfile(user);
        return AjaxResult.success();
    }

}
